package com.hanxiaozhang.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.web.context.request.RequestContextListener;

import javax.servlet.http.HttpServletResponse;


/**
 * 功能描述: <br>
 * 〈资源服务器配置类〉
 *
 * @Author:hanxiaozhang
 * @Date: 2020/7/31
 */
@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http
                .csrf().disable()
                // 配置异常处理器
                .antMatcher("/**")
                .exceptionHandling()
                .authenticationEntryPoint((request, response, authException) -> response.sendError(HttpServletResponse.SC_UNAUTHORIZED))
                .and()
                // 所有请求都需要授权,除去/actuator/**
                .authorizeRequests()
                .antMatchers("/actuator/**","/files/**").permitAll()
                .anyRequest().authenticated()
                .and()
                .httpBasic();
    }

    /**
     *  解决如下问题：
     *  Could not fetch user details: class org.springframework.beans.factory.BeanCreationException,
     *  Error creating bean with name 'scopedTarget.oauth2ClientContext':
     *  Scope 'request' is not active for the current thread;
     *  https://blog.csdn.net/wzygis/article/details/21191549
     *
     * @return
     */
    @Bean
    @Order(0)
    public RequestContextListener requestContextListener() {
        return new RequestContextListener();
    }

}